<template>
  <div class="user-page">
    <van-nav-bar class="page-nav-bar" title="个人中心">
      <van-icon @click="$router.go(-1)" slot="left" name="arrow-left" />
    </van-nav-bar>
    <input @change="inputChange" ref="inputFile" type="file" hidden>
    <van-cell title="头像" @click="$refs.inputFile.click()" is-link>
      <van-image
        class="avatar"
        round
        :src="user.photo"
      />
    </van-cell>
    <van-cell title="昵称" @click="showEditUserNickName = true" :value="user.name" is-link />
    <van-cell title="性别" @click="showEditUserGender = true" :value="user.gender ? '女' : '男'" is-link />
    <van-cell title="生日" @click="showEditBirthday = true" :value="user.birthday" is-link />

    <!-- 编辑昵称弹层 -->
    <van-popup v-model="showEditUserNickName" position="bottom" :style="{ height: '100%' }">
      <EditNickname v-if="showEditUserNickName" v-model="user.name" @on-cancel="showEditUserNickName = false"/>
    </van-popup>

    <!-- 编辑性别弹层 -->
    <van-popup v-model="showEditUserGender" position="bottom">
      <EditGender v-if="showEditUserGender" v-model="user.gender" @on-cancel="showEditUserGender = false" />
    </van-popup>

    <!-- 编辑生日弹层 -->
    <van-popup v-model="showEditBirthday" position="bottom">
      <EditBirthday v-if="showEditBirthday" @on-cancel="showEditBirthday = false" v-model="user.birthday" />
    </van-popup>

    <!-- 编辑头像弹层 -->
    <van-popup style="height: 100%;" v-model="showEditAvatar" position="bottom">
      <EditAvatar @on-success="user.photo = $event" @on-cancel="showEditAvatar = false" :imgUrl="imgUrl"/>
    </van-popup>
  </div>
</template>

<script>
import { getUserDetail } from '@/api/user.js'
import EditNickname from './components/edit-nickname.vue'
import EditGender from './components/edit-gender.vue'
import EditBirthday from './components/edit-birthday.vue'
import EditAvatar from './components/edit-avatar.vue'
export default {
  data() {
    return {
      user: {},
      showEditUserNickName: false, // 编辑昵称弹层显示与隐藏
      showEditUserGender: false, // 编辑性别弹层显示与隐藏
      showEditBirthday: false, // 编辑生日弹层显示与隐藏
      showEditAvatar: false,
      imgUrl: null
    }
  },

  components: {
    EditNickname,
    EditGender,
    EditBirthday,
    EditAvatar
  },

  created() {
    this.loadUserProfile()
  },

  methods: {
    // 加载用户资料
    async loadUserProfile() {
      try {
        const res = await getUserDetail()
        this.user = res.data
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    inputChange(e) {
      const file = e.target.files[0]
      this.imgUrl = window.URL.createObjectURL(file)
      this.showEditAvatar = true
      e.target.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.user-page {
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
